from django.core.exceptions import ObjectDoesNotExist
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.decorators import permission_classes, action
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

import backend.permissions
from backend import helper
from passages.filter import PassageFilter
from passages.models import Passage
from passages.permissions import PassagePermission
from passages.serializers import PassageSerializer


@permission_classes([PassagePermission,
                     backend.permissions.IsManualAuthenticatedOrReadOnly])
class PassageViewSet(helper.MyModelViewSet):
    queryset = Passage.objects.all().order_by('created_at').reverse()
    serializer_class = PassageSerializer
    filter_class = PassageFilter
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]

    ordering_fields = ['created_at', 'likes']
    search_fields = ['=author__username', 'category', 'title']

    @action(methods=['POST'], detail=True,
            permission_classes=[IsAuthenticated])
    def thumbs_up(self, request, pk):
        """
        未实名和实名用户均可点赞。
        通过<pk>索引，对指定帖子点赞。
        暂时没有限制点赞次数（一个人可以让点赞数不停增加，maybe前端考虑限制一次，还要实现throttle）
        """
        instance = Passage.objects.get(id=pk)
        if not instance:
            raise ObjectDoesNotExist()

        instance.likes += 1
        instance.save()

        return Response(data={
            "success": True,
            "code": 200,
            "msg": "点赞成功",
            "likes": instance.likes,
        }, status=status.HTTP_200_OK)


